<?php

namespace App\Library\Traits;

trait AttributeTrait
{
    public function setTagAttribute($value): void
    {
        $this->attributes['tag'] = empty($value) ? null : json_encode(explode(',', $value));
    }

    public function setMainImgIdsAttribute($value): void
    {
        if (empty($value)) $this->attributes['main_img_ids'] = null;
        else $this->attributes['main_img_ids'] = json_encode(explode(',', $value));
    }


    public function getMainImgIdsAttribute($value): ?string
    {
        if (empty($value)) return null;
        else return implode(',', json_decode($value, true));
    }

    public function getSpecJsonAttribute($value): ?string
    {
        if (empty($value)) return null;
        else return implode(',', json_decode($value, true));
    }

    public function setSpecJsonAttribute($value): void
    {
        if (empty($value)) $this->attributes['spec_json'] = null;
        else $this->attributes['spec_json'] = json_encode(explode(',', $value));
    }

    public function setDescImgIdsAttribute($value): void
    {
        if (empty($value)) $this->attributes['desc_img_ids'] = null;
        else $this->attributes['desc_img_ids'] = json_encode(explode(',', $value));
    }

    public function getDescImgIdsAttribute($value): ?string
    {
        if (empty($value)) return null;
        else return implode(',', json_decode($value, true));
    }

    public function setProductSpecialStartTimeAttribute($value): void
    {
        if (is_null($value)) $this->attributes['product_special_start_time'] = 0;
        else $this->attributes['product_special_start_time'] = now()->parse($value)->timestamp;
    }

    public function getProductSpecialStartTimeAttribute($value): ?string
    {
        if ($value === 0) return null;
        else return now()->timestamp($value);
    }

    public function getProductSpecialEndTimeAttribute($value): ?string
    {
        if ($value === 0) return null;
        else return now()->timestamp($value);
    }

    public function setProductSpecialEndTimeAttribute($value): void
    {
        if (is_null($value)) $this->attributes['product_special_end_time'] = 0;
        else $this->attributes['product_special_end_time'] = now()->parse($value)->timestamp;
    }

    public function setPsIdJsonAttribute($value): void
    {
        if (is_null($value)) $this->attributes['ps_id_json'] = null;
        else {
            foreach (explode(',', $value) as $v) $arr[] = (int)$v;
            $this->attributes['ps_id_json'] = empty($arr) ? null : json_encode($arr);
        }
    }
}
